﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Diagnostics;
using System.Management;

namespace FBKPI.ReportHandler
{
    /// <summary>
    /// Summary description for AnnualReportHandler
    /// </summary>
    public class AnnualReportHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string msg = this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = string.Empty;
            try {
                int year = Convert.ToInt32( HttpContext.Current.Request.QueryString["Year"]);
                Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["User"]));
                string path = System.Configuration.ConfigurationManager.AppSettings["AnnualReportPath"].ToString();
                string outputFilename = CurrUser.ID.ToString() + "_" + year.ToString() + "_" + DateTime.Now.Hour.ToString() +  DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".xls";
                string outputPath = System.Configuration.ConfigurationManager.AppSettings["ExportAnnualReportPath"].ToString() + outputFilename;

                ReportFacade Rf = new ReportFacade();
                msg = Rf.GenerateExcel(year, CurrUser, path, outputPath);
            }
            catch (Exception ex)
            {
                Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
                logwriter.WriteLog(ex.Message, ex.StackTrace.ToString());
                msg = "Error while generate excel file, please contact IT suppport";
            }
            finally
            {
                //kill idle excel process
                foreach (Process p in Process.GetProcessesByName("excel"))
                {
                    PerformanceCounter cpuUsage = new PerformanceCounter("Process", "% Processor Time", "_Total");
                    PerformanceCounter pcProcess = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
                    double cpu = Math.Round(pcProcess.NextValue() / cpuUsage.NextValue() * 100, 2);

                    if (Double.IsNaN(cpu))
                        cpu = 0;

                    if (cpu == 0)
                    {
                        string query = "Select * From Win32_Process Where ProcessID = " + p.Id.ToString();
                        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                        ManagementObjectCollection processlist = searcher.Get();

                        foreach (ManagementObject obj in processlist)
                        {
                            string[] argList = new string[] { string.Empty, string.Empty };
                            int retVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));

                            if (retVal == 0)
                            {
                                string User = argList[0];
                                if (User == System.Configuration.ConfigurationManager.AppSettings["OwnerExcelProcess"].ToString())
                                    p.Kill();
                            }
                        }
                    }
                }
            }

            var gridData = new
            {
                msg
            };
            var JSONSerializer = new JavaScriptSerializer();
            return JSONSerializer.Serialize(gridData);
        }
    }
}